package com.ucode.application.controller.crm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.form.crm.FollowupRecordForm;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.application.vo.crm.FollowupRecordVo;
import com.ucode.crm.mode.Business;
import com.ucode.crm.mode.FollowupRecord;
import com.ucode.crm.service.BusinessService;
import com.ucode.crm.service.FollowupRecordService;
import com.ucode.oss.model.FileInfo;
import com.ucode.oss.service.FileInfoService;
import com.ucode.sys.model.User;
import com.ucode.sys.service.UserService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="跟进记录")
@RestController
@RequestMapping("/cms-followupRecord")
@Validated
public class FollowupRecordController {
    private static Log log = LogFactory.get();
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private FollowupRecordService followupRecordService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    
    @Autowired
    private UserService userService;
    @ApiOperation("跟进记录")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="目标类型:1线索2客户3商机4合同",required=true)  @RequestParam(value = "targetType",required=true) Integer targetType,
            @ApiParam(value ="跟进目标Id",required=true)  @RequestParam(value = "targetId",required=true) Long targetId,
            @ApiParam(value ="联系人Id",required=false)  @RequestParam(value = "contactsId",required=false) Long contactsId,
            @ApiParam(value ="关键字",required=false)  @RequestParam(value = "keyword",required=false) String keyword,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        
        try {
            Paginator<FollowupRecord> paginator = followupRecordService.queryPage(keyword, targetType, targetId, contactsId, pageNum, pageSize);
            Paginator<FollowupRecordVo> page = new Paginator<>(paginator.getTotal(), paginator.getCurrentPage(), paginator.getRows());
            if(paginator != null && CollUtil.isNotEmpty(paginator.getList())){
                List<Long> fileIds = new ArrayList<Long>();
                Set<Long> userIds = new HashSet<Long>(); 
                
                Set<Long> contactsIds = new HashSet<Long>(); 
                for(FollowupRecord record : paginator.getList()){
                    userIds.add(record.getCreateUserId());
                    if(StrUtil.isNotBlank(record.getImgIds())){
                        String[] values = record.getImgIds().split(",");
                        for(String value : values){
                            fileIds.add(Long.valueOf(value));
                        }
                    }
                    if(StrUtil.isNotBlank(record.getFileIds())){
                        String[] values = record.getFileIds().split(",");
                        for(String value : values){
                            fileIds.add(Long.valueOf(value));
                        }
                    }
                    
                    if(record.getContactsId() != null && record.getContactsId().longValue() > 0){
                        contactsIds.add(record.getContactsId());
                    }
                    
                    if(targetType == 2){
                        
                    }
                    
                }
                
                CompletableFuture<Map<String, FileInfo>> completableFutureFiles = CompletableFuture.supplyAsync(() -> {
                    Map<String, FileInfo> fileMap = new HashMap<>(); 
                    if(CollUtil.isNotEmpty(fileIds)){
                        List<FileInfo> files = fileInfoService.findByIds(fileIds);
                        if(CollUtil.isNotEmpty(files)){
                            for(FileInfo file : files){
                                fileMap.put(file.getId().toString(), file);
                            }
                        }
                    }
                    return fileMap;
                });
                
                CompletableFuture<Map<Long, User>> completableFutureUsers = CompletableFuture.supplyAsync(() -> {
                    List<User> ulist = userService.findByIds(new ArrayList<>(userIds));
                    if(CollUtil.isNotEmpty(ulist))
                        return  ulist.stream().collect(Collectors.toMap(User::getId,Function.identity(),(key1, key2) -> key1));
                    return new HashMap<>();
                });
                
                Map<String, FileInfo> fileMap = completableFutureFiles.get();
                Map<Long, User> userMap = completableFutureUsers.get();
                
                List<FollowupRecordVo> vos = new ArrayList<>();
                for(FollowupRecord followupRecord : paginator.getList()){
                    User user = userMap.get(followupRecord.getCreateUserId());
                    String realname = null, headImg = null;
                    if(user != null){
                        realname = user.getRealname();
                        headImg = user.getHeadImg();
                    }
                    String _imgIds = followupRecord.getImgIds();
                    List<FileInfo> imgs = new ArrayList<>();
                    if(StrUtil.isNotBlank(_imgIds)){
                        String[] ids = _imgIds.split(",");
                        for(String id : ids){
                            FileInfo img = fileMap.get(id);
                            if(img != null)
                                imgs.add(img);
                        }
                    }
                    
                    String _fileIds = followupRecord.getFileIds();
                    List<FileInfo> files = new ArrayList<>();
                    if(StrUtil.isNotBlank(_fileIds)){
                        String[] ids = _fileIds.split(",");
                        for(String id : ids){
                            FileInfo file = fileMap.get(id);
                            if(file != null)
                                files.add(file);
                        }
                    }
                    
                    FollowupRecordVo vo = new FollowupRecordVo(followupRecord, imgs,files, realname, headImg);
                    vos.add(vo);
                }
                page.setList(vos);
            }
            return ResponseResult.success(page);
        } catch (Exception e) {
            log.error(e);
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }
    
    @ApiOperation(value="发布")
    @PostMapping("/release")
    public ResponseResult<Object> release(@Validated @RequestBody FollowupRecordForm form) {
        FollowupRecord followupRecord = new FollowupRecord();
        followupRecord.setContent(form.getContent());
        if(CollUtil.isNotEmpty(form.getImgIds()))
            followupRecord.setImgIds(CollUtil.join(form.getImgIds(), ","));
        
        if(CollUtil.isNotEmpty(form.getFileIds()))
            followupRecord.setFileIds(CollUtil.join(form.getFileIds(), ","));
        
        followupRecord.setActivityType(form.getActivityType());
        followupRecord.setTargetType(form.getTargetType());
        followupRecord.setTargetId(form.getTargetId());
        followupRecord.setContactsId(form.getContactsId());
        followupRecord.setNextTime(form.getNextTime());
        followupRecord.setCreateUserId(currentLoginUserService.getCurrentUserId());
        
        if(form.getTargetType().intValue() == 2){
            followupRecord.setCustomerId(form.getTargetId());
        }else if(form.getTargetType().intValue() == 3){
            Business business = businessService.findById(form.getTargetId());
            if(business == null){
                throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
            }
            followupRecord.setCustomerId(business.getCustomerId());
        }else if(form.getTargetType().intValue() == 4){
            
        }
        
        int i = followupRecordService.insert(followupRecord);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @ApiOperation(value="删除")
    @ApiImplicitParam(name = "id", value = "跟进记录ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/delete/{id}")
    public ResponseResult<Object> delete(@PathVariable(name="id",required=true) Long id) {
        followupRecordService.delete(id);
        return ResponseResult.success();
    }
    
}
